package vn.intelsoft.vlogvn.instance;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class Instance {
	private static final int BUFFER_SIZE = 0;

	public static HashMap<String, Bitmap> datas = new HashMap<String, Bitmap>();

	@SuppressWarnings("deprecation")
	public static int width(Context context) {
		return ((Activity) context).getWindowManager().getDefaultDisplay()
				.getWidth();
	}

	@SuppressWarnings("deprecation")
	public static int height(Context context) {
		return ((Activity) context).getWindowManager().getDefaultDisplay()
				.getHeight();
	}
	
	public static boolean CheckFileExists(String path){
		File file = new File(path);
		if (file.exists()) {
			return true;
		}else{
			return false;
		}
	}

	public static boolean isNetworkAvailable(Activity activity) {
		ConnectivityManager connectivity = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static String read(Context context, String file) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					context.getAssets().open(file)));
			String word;
			while ((word = reader.readLine()) != null) {
				sb.append(word);
			}

		} catch (IOException e) {
			Log.e(e.getMessage());
		}

		return sb.toString();
	}

	public static Bitmap getBitmapFromAsset(Context context, String path) {
		Bitmap bitmap = null;
		try {
			InputStream input = context.getResources().getAssets().open(path);
			if (input != null) {
				bitmap = BitmapFactory.decodeStream(input);
			}
		} catch (Exception e) {
			Log.e("Could not get Bitmap '" + path + "' because "
					+ e.getMessage());
		}

		return bitmap;
	}

	public static Bitmap get(Context c, String path) {
		synchronized (datas) {
			if (!datas.containsKey(path)) {
				try {
					Bitmap bitmap = null;
					if (path.contains(Environment.getExternalStorageDirectory()
							.toString())) {
						bitmap = Instance.decodeFileBase(new File(path));
					} else {
						try {
							InputStream input = c.getResources().getAssets()
									.open(path);
							if (input != null) {
								bitmap = BitmapFactory.decodeStream(input);
							}
						} catch (Exception e) {
							Log.e("Could not get Bitmap '" + path
									+ "' because " + e.getMessage());
						}
					}

					datas.put(path, bitmap);
				} catch (Exception e) {
					Log.e("Could not get Bitmap '" + path + "' because "
							+ e.getMessage());
					return null;
				}
			}
			return datas.get(path);
		}
	}

	// catch out of memory get 60% image original
	public static final Bitmap decodeFileBase(File f) {
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);
			final int REQUIRED_SIZE = 512;

			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp *= 0.8;
				height_tmp *= 0.8;
				scale *= 2;
			}
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			Bitmap bitmap = null;
			try {
				bitmap = BitmapFactory.decodeStream(new FileInputStream(f),
						null, o2);
			} catch (final Throwable e) {
				System.gc();
			}
			return bitmap;
		} catch (final Throwable e) {
			System.gc();
			return null;
		}
	}

	public static void removeAll() {
		List<String> keys = new ArrayList<String>(datas.keySet());
		for (int i = 0; i < keys.size(); i++) {
			if (datas.get(keys.get(i)) != null) {
				datas.get(keys.get(i)).recycle();
				datas.remove(keys.get(i));
			}
		}

		datas = new HashMap<String, Bitmap>();
	}

	public static void remove(String path) {
		try {
			if(datas.get(path) != null){
				datas.get(path).recycle();
				datas.remove(path);
			}
		} catch (Exception e) {
			Log.e(e.getMessage());
		}
	}

	public static Bitmap loadBitmapFromView(View v) {
		Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
				Bitmap.Config.ARGB_8888);
		Canvas c = new Canvas(b);
		// v.layout(0, 0, v.getWidth(), v.getHeight());
		v.draw(c);
		return b;
	}
	
	public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
	    int width = bm.getWidth();
	    int height = bm.getHeight();
	    float scaleWidth = ((float) newWidth) / width;
	    float scaleHeight = ((float) newHeight) / height;
	    // CREATE A MATRIX FOR THE MANIPULATION
	    Matrix matrix = new Matrix();
	    // RESIZE THE BIT MAP
	    matrix.postScale(scaleWidth, scaleHeight);

	    // "RECREATE" THE NEW BITMAP
	    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
	    return resizedBitmap;
	}

	public final static String saveBitmapNoMedia(Bitmap bitmap, String name,
			String extension) {
		String folderName = "/Bang chu cai/";
		createFolder(folderName);
		// set with extension = PNG or JPEG
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		bitmap.compress((extension.equals("PNG") ? Bitmap.CompressFormat.PNG
				: Bitmap.CompressFormat.JPEG), 100, bytes);
		String pathImage = null;

		// you can create a new file name "test.jpg" in sdcard folder.
		File f = new File(Environment.getExternalStorageDirectory()
				+ folderName + name + ".nomedia");
		pathImage = f.getAbsolutePath();

		try {
			f.createNewFile();
			FileOutputStream fo = new FileOutputStream(f);
			fo.write(bytes.toByteArray());

			// remember close de FileOutput
			fo.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			pathImage = null;
			Log.e(e.getMessage());
		}

		return pathImage;
	}

	public final static void createFolder(String path) {
		if (!path.startsWith("/"))
			path = "/" + path;
		path = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ path;
		File dataFile = new File(path);
		if (!dataFile.exists())
			dataFile.mkdirs();
	}

	public static void setViewGroupTypeface(ViewGroup container, Context context) {
		final int children = container.getChildCount();
		Typeface typeface = Typeface.createFromAsset(context.getAssets(),
				"UVNBAISAU_N.TTF");

		for (int i = 0; i < children; i++) {
			View child = container.getChildAt(i);
			if (child instanceof TextView) {
				setTextViewTypeface((TextView) child, context);
			} else if (child instanceof ViewGroup) {
				setViewGroupTypeface((ViewGroup) child, context);
			}
		}
	}

	public static void setTextViewTypeface(TextView textView, Context context) {
		Typeface typeface = Typeface.createFromAsset(context.getAssets(),
				"UVNBAISAU_N.TTF");
		textView.setTypeface(typeface);
	}

	public static void setButtonTypeface(Button button, Context context) {
		Typeface typeface = Typeface.createFromAsset(context.getAssets(),
				"UVNBAISAU_N.TTF");
		button.setTypeface(typeface);
	}

	public static final Character[] a = new Character[] { 'a', 'à', 'á', 'ạ',
			'ả', 'ã' };
	public static final Character[] aw = new Character[] { 'â', 'ầ', 'ấ', 'ậ',
			'ẩ', 'ẫ' };
	public static final Character[] aa = new Character[] { 'ă', 'ằ', 'ắ', 'ặ',
			'ẳ', 'ẵ' };
	public static final Character[] e = new Character[] { 'e', 'è', 'é', 'ẹ',
			'ẻ', 'ẽ' };
	public static final Character[] ee = new Character[] { 'ê', 'ề', 'ế', 'ệ',
			'ể', 'ễ' };
	public static final Character[] i = new Character[] { 'i', 'ì', 'í', 'ị',
			'ỉ', 'ĩ' };
	public static final Character[] o = new Character[] { 'o', 'ò', 'ó', 'ọ',
			'ỏ', 'õ' };
	public static final Character[] oo = new Character[] { 'ô', 'ồ', 'ố', 'ộ',
			'ổ', 'ỗ' };
	public static final Character[] ow = new Character[] { 'ơ', 'ờ', 'ớ', 'ợ',
			'ở', 'ỡ' };
	public static final Character[] u = new Character[] { 'u', 'ù', 'ú', 'ụ',
			'ủ', 'ũ' };
	public static final Character[] uw = new Character[] { 'ư', 'ừ', 'ứ', 'ự',
			'ử', 'ữ' };
	public static final Character[] y = new Character[] { 'y', 'ỳ', 'ý', 'ỵ',
			'ỷ', 'ỹ' };

	public static Character unmark(char ch) {
		Character[][] all = new Character[][] { a, aw, aa, e, ee, i, o, oo, ow,
				u, uw, y };
		for (Character[] first : all) {
			for (Character second : first) {
				if (ch == second) {
					return first[0];
				}
			}
		}

		return ch;
	}

	public static String unmark(String str) {
		return String.valueOf(unmark(str.charAt(0)));
	}
	
	public static String getDurationString(int seconds) {

	    int hours = seconds / 3600;
	    int minutes = (seconds % 3600) / 60;
	    seconds = seconds % 60;

	    return twoDigitString(hours) + ":" + twoDigitString(minutes) + ":" + twoDigitString(seconds);
	}

	public static String twoDigitString(int number) {

	    if (number == 0) {
	        return "00";
	    }

	    if (number / 10 == 0) {
	        return "0" + number;
	    }

	    return String.valueOf(number);
	}

}
